package si.yun.web;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.exceptions.ClientException;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import si.yun.entity.QQUserInfo;
import si.yun.entity.SyBeforeUser;
import si.yun.entity.SyLoginRecord;
import si.yun.entity.WeiXinUserInfo;
import si.yun.service.LoginService;
import si.yun.utils.*;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: ThinkManage
 * @description: 移动登录Web层
 * @author: 崔晓晨
 * @create: 2021-10-11 16:27
 **/
@RestController
@RequestMapping("/beforeUser")
@PropertySource({"config/config.properties"})
public class LoginController {
    @Autowired
    private LoginService loginService;
    /*获取服务器路径*/
    @Value("${path1}")
    private String path;
    @Autowired
    private TestAliUpload testAliUpload;
    //微信应用appid
//    private String WxAppId = "wx862e03dc86ea9a8d";
    private String WxAppId = "wx41b9b9c0aad3b6bb";
    //微信应用密钥
//    private String WxAppSecret = "b57018f90d4cf21ae483d446f0dee0e6";
    private String WxAppSecret = "5b68de5387350672060ff98b9bb0f40c";

    /**
     * @Description  查看用户登录数据
     * @return si.yun.utils.JsonData 
     * @Date 2021/10/12 20:58
     **/
    @PostMapping("/selBeforeLoginInfo")
    public JsonData login(String phone, String pwd, HttpSession session){
        SyBeforeUser beforeUser = loginService.selBeforeLoginInfo(phone, pwd);
        if(beforeUser!=null){
            boolean verify = Md5Utils.verify(pwd, beforeUser.getPassword());
            if(verify){
                if(beforeUser.getStatus()==2){
                    if(beforeUser.getAvatarUrl()!=null && beforeUser.getAvatarUrl().length()!=0 && beforeUser.getAvatarUrl()!="null"){
                        if(beforeUser.getAvatarUrl().indexOf("http") == -1){
                            beforeUser.setAvatarUrl(path+beforeUser.getAvatarUrl());
                        }
                    }
                    session.setAttribute("user",beforeUser);
                    return beforeUser!=null?JsonData.buildSuccess(beforeUser):JsonData.buildError("服务器错误");
                }else{
                    //账号封停标志
                    Integer logoError = 500;
                    return logoError!=0?JsonData.buildSuccess(logoError):JsonData.buildError("服务器错误");
                }
            }else{
                //登陆失败标志
                Integer logoError = 400;
                return logoError!=0?JsonData.buildSuccess(logoError):JsonData.buildError("服务器错误");
            }
        }else{
            //登陆失败标志
            Integer logoError = 400;
            return logoError!=0?JsonData.buildSuccess(logoError):JsonData.buildError("服务器错误");
        }
    }
    /**
     * @Description  调用短信生成验证码
     * @return si.yun.utils.JsonData
     * @Date 2021/10/13 11:17
     **/
    @PostMapping("/getSmsInfo")
    public JsonData getSmsInfo(String phone){
        //生成6位验证码
        String smsInfo = GetRandomUtil.randomCode();
        System.out.println(phone);
        //调用短信
        try {
            SendMessage.sendSms(phone, smsInfo);
        } catch (ClientException e) {
            e.printStackTrace();
        }
        Map<String,Object> map = new HashMap<>();
        map.put("smsInfo",smsInfo);
        System.out.println(smsInfo+"=============================================");
        return map!=null?JsonData.buildSuccess(map):JsonData.buildError("服务器错误");
    }
    /**
     * @Description  注册前台用户
     * @return si.yun.utils.JsonData
     * @Date 2021/10/13 11:19
     **/
    @PostMapping("/registerBeforeUser")
    public JsonData registerBeforeUser(String phone,String password,String nickName){
        //判断创建的用户是否存在
        List<String> list = loginService.selPhones();
        if(list.contains(phone)){
            //存在返回 400
            int repeatUser = 400;
            return repeatUser!=0?JsonData.buildSuccess(repeatUser):JsonData.buildError("服务器错误");
        }else{
            //不存在创建用户 返回成功 1
            int register = loginService.registerBeforeUser(phone,password,nickName);
            return register!=0?JsonData.buildSuccess(register):JsonData.buildError("服务器错误");
        }
    }
    /**
     * @Description  使用手机账号快速登录系统
     * @return si.yun.utils.JsonData
     * @Date 2021/10/13 11:19
     **/
    @PostMapping("/phoneRegisterUser")
    public JsonData phoneRegisterUser(String phone,String nickName){
        //判断创建的用户是否存在
        List<String> list = loginService.selPhones();
        if(list.contains(phone)){
            //存在直接登录
            SyBeforeUser beforeUser = loginService.selPhoneLoginInfo(phone);
            if(beforeUser.getStatus()==2){
                return beforeUser!=null?JsonData.buildSuccess(beforeUser):JsonData.buildError("服务器错误");
            }else{
                //账号封停标志
                Integer logoError = 500;
                return logoError!=0?JsonData.buildSuccess(logoError):JsonData.buildError("服务器错误");
            }
        }else{
            //不存在创建用户 返回成功 1
            System.out.println(phone+nickName);
            int register = loginService.phoneRegisterUser(phone,nickName);
            if(register!=0){
                SyBeforeUser beforeUser = loginService.selPhoneLoginInfo(phone);
                return beforeUser!=null?JsonData.buildSuccess(beforeUser):JsonData.buildError("服务器错误");
            }else{
                int nullNum = 400;
                return nullNum!=0?JsonData.buildSuccess(nullNum):JsonData.buildError("服务器错误");
            }
        }
    }
    /**
     * @Description  调用忘记密码短信生成验证码
     * @return si.yun.utils.JsonData
     * @Date 2021/10/13 11:17
     **/
    @PostMapping("/getPwdSmsInfo")
    public JsonData getPwdSmsInfo(String phone){
        //判断创建的用户是否存在
        List<String> list = loginService.selPhones();
        if(list.contains(phone)){
            //存在调用短信
            //生成6位验证码
            String smsInfo = GetRandomUtil.randomCode();
            //调用短信
            try {
                SendMessage.sendSms(phone, smsInfo);
            } catch (ClientException e) {
                e.printStackTrace();
            }
            Map<String,Object> map = new HashMap<>();
            map.put("smsInfo",smsInfo);
            System.out.println(smsInfo+"=============================================");
            return map!=null?JsonData.buildSuccess(map):JsonData.buildError("服务器错误");
        }else{
            //不存在返回400
            int nullNum = 400;
            Map<String,Object> map = new HashMap<>();
            map.put("smsInfo",nullNum);
            System.out.println(nullNum+"=============================================");
            return map!=null?JsonData.buildSuccess(map):JsonData.buildError("服务器错误");
        }
    }
    /**
     * @Description  忘记  修改密码
     * @return si.yun.utils.JsonData
     * @Date 2021/10/13 13:54
     **/
    @PostMapping("/updBeforeUserPwd")
    public JsonData updBeforeUserPwd(String phone,String password){
        Integer upd = loginService.updBeforeUserPwd(phone, password);
        return upd!=0?JsonData.buildSuccess(upd):JsonData.buildError("服务器错误");
    }
    /**
     * @Description  退出登录
     * @return si.yun.utils.JsonData
     * @Date 2021/10/18 18:39
     **/
    @GetMapping("/quitLoginApi")
    public JsonData quitLoginApi(HttpSession session){
        session.removeAttribute ("user");
        return JsonData.buildSuccess(true);
    }
    public String  uploadFile(@RequestParam MultipartFile files) throws IllegalStateException, IOException {
        //上传到服务器
        String newName = testAliUpload.upload(files);
        return newName;
    }
    /**
     * @Description  更改用户头像
     * @return si.yun.utils.JsonData
     * @Date 2021/10/20 8:40
     **/
    @PostMapping("/uploadImg")
    public JsonData uploadImg(@RequestParam("file") MultipartFile file,Integer userId) throws IllegalStateException, IOException {
        String newName = uploadFile(file);
        System.out.println(newName+"=================================================");
        //获取用户的头像path 删除服务器中旧的头像
        //        Map<String, String> stringStringMap = loginService.selOldUserImg(userId);
        //        String avatarUrl = stringStringMap.get("avatarUrl");
        //        if(avatarUrl!=null && avatarUrl.length()!=0 && avatarUrl!="null"){
        //            if(avatarUrl.indexOf("http") == -1){
        //                testAliUpload.delete(avatarUrl);
        //            }
        //        }
        Integer upd = loginService.updBeforeUserImg(newName, userId);
        SyBeforeUser beforeUser = loginService.selUserAllInfo(userId);
        return beforeUser != null ? JsonData.buildSuccess(beforeUser) : JsonData.buildError("服务器异常！请耐心等待修复！");
    }
    /**
     * @Description  更新用户信息
     * @return si.yun.utils.JsonData
     * @Date 2021/10/20 9:32
     **/
    @PostMapping("/updBeforeInfo")
    public JsonData updBeforeInfo(SyBeforeUser beforeUser){
        Integer upd = loginService.updBeforeInfo(beforeUser);
        SyBeforeUser user;
        if(upd==1){
            user = loginService.selUserAllInfo(beforeUser.getUserId());
        }else{
            user=null;
        }
        return beforeUser != user ? JsonData.buildSuccess(user) : JsonData.buildError("服务器异常！请耐心等待修复！");
    }
    /**
     * @Description  添加登录日志
     * @return si.yun.utils.JsonData
     * @Date 2021/11/8 16:44
     **/
    @PostMapping("/addLoginLogo")
    public JsonData addLoginLogo(SyLoginRecord loginRecord){
        Integer add = loginService.addLoginLogo(loginRecord);
        return add != 0 ? JsonData.buildSuccess(add) : JsonData.buildError("服务器异常！请耐心等待修复！");
    }
    /**
     * 添加qq用户，若存在直接登录
     * @param qqUserInfo
     * @return
     */
    @PostMapping("/addQQUserInfo")
    public JsonData addQQUserInfo(QQUserInfo qqUserInfo){
        SyBeforeUser userInfo = loginService.InicioDeSesiónDeTerceros("qq", qqUserInfo.getUnionid(), qqUserInfo.getNickname(), qqUserInfo.getFigureurl_qq());
        return userInfo!=null?JsonData.buildSuccess(userInfo):JsonData.buildError("服务器异常！请耐心等待修复！");
    }

    /**
     * 添加微信用户，若存在直接登录
     * @param weiXinUserInfo
     * @return
     */
    @PostMapping("/addWeiXinUserInfo")
    public JsonData addWeiXinUserInfo(WeiXinUserInfo weiXinUserInfo){
        SyBeforeUser userInfo = loginService.InicioDeSesiónDeTerceros("weixin", weiXinUserInfo.getUnionid(), weiXinUserInfo.getNickname(), weiXinUserInfo.getHeadimgurl());
        return userInfo!=null?JsonData.buildSuccess(userInfo):JsonData.buildError("服务器异常！请耐心等待修复！");
    }

    /**
     * 为微信进行临时令牌的获取，通过临时信息获取用户信息
     * @param code
     * @return
     */
    @PostMapping("getWXUserInfo")
    public JsonData getWXUserInfo(String code){
        String getToken = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
        getToken = getToken.replace("APPID",WxAppId).replace("SECRET",WxAppSecret).replace("CODE",code);
        //System.out.println("code请求："+getToken);
        String token = HttpClentUtil.get(getToken);
        Map map = JSON.parseObject(token);
        //获取到了关键的令牌和openid后，
        //就可以正式开始查询微信用户的信息，完成我们要做的微信绑定
        String getUserInfo = "https://api.weixin.qq.com/sns/userinfo?access_token=TOKEN&openid=OPENID";
        String access_token = (String) map.get("access_token");
        String openid = (String) map.get("openid");
        getUserInfo = getUserInfo.replace("TOKEN", access_token).replace("OPENID", openid);
        //System.out.println("token请求："+getUserInfo);
        String userInfo = HttpClentUtil.get(getUserInfo);
        //将json字符串转java对象
        WeiXinUserInfo weiXinUserInfo = JSON.parseObject(userInfo,WeiXinUserInfo.class);
        //进行第三方登录
        SyBeforeUser user = loginService.InicioDeSesiónDeTerceros("weixin", weiXinUserInfo.getUnionid(), weiXinUserInfo.getNickname(), weiXinUserInfo.getHeadimgurl());
        if(user.getAvatarUrl()!=null && user.getAvatarUrl().length()!=0 && user.getAvatarUrl()!="null"){
            if(user.getAvatarUrl().indexOf("http") == -1){
                user.setAvatarUrl(path+user.getAvatarUrl());
            }
        }
        return user!=null?JsonData.buildSuccess(user):JsonData.buildError("服务器异常！请耐心等待修复！");
    }
}
